﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace OnlineManagement.Web.userControl
{
    
    public partial class UCSowsSettings :BaseSowUserControl
    {
        protected int hoggeryId=0;
        private string strPath = "";
        
        protected void Page_Load(object sender, EventArgs e)
        {
            strPath = this.Page.Request.ServerVariables["PATH_INFO"];
           
            //btnSave.Click += new EventHandler(btnSave_Click);
            btnSearch.Click+=new EventHandler(btnSearch_Click);
            btnAllSearch.Click += new EventHandler(btnAllSearch_Click);

            rptShow.ItemDataBound += new RepeaterItemEventHandler(rptShow_ItemDataBound);
            if(!Page.IsPostBack){
                hoggeryId = HoggeryID;
                if (hoggeryId == 0)
                {
                    panEmpty.Visible = true;
                    return;
                }
               // BindDropDownLists(hoggeryId);
                BindRepeater(hoggeryId,string.Empty);
            }
        }

        void btnAllSearch_Click(object sender, EventArgs e)
        {
            Response.Redirect("./SowManagement.aspx");
        }
       

        //void btnSave_Click(object sender, EventArgs e)
        //{
        //    panShow.Visible = false;
        //    string bitId = txtBitId.Text.Trim();
        //    string dateJoinStr = txtDateIncome.Text;
        //    DateTime dateJoin;
        //    DateTime dateBirthday;
        //    Guid pigPenId;
        //    Guid pigTypeId;
        //    Guid propagateStateID;
        //    int sourceId;
        //    int hybridizationCount = 0;
        //    int propagateCount = 0;
        //    hoggeryId = HoggeryID;
        //    if (hoggeryId == 0 || string.IsNullOrEmpty(txtHoggeryName.Text))
        //    {
        //        Common.MessageBox.PrintMsg(panMsg, Common.MsgLevelEnum.attention, Common.PubMsg.NoOnlineMgrData);
        //        return;
        //    }
        //    if (string.IsNullOrEmpty(bitId))
        //    {
        //        Common.MessageBox.PrintMsg(panMsg, Common.MsgLevelEnum.attention, Common.PubMsg.SowBitIDISEmpty);
        //        return;
        //    }
        //    if (!DateTime.TryParse(dateJoinStr, out dateJoin))
        //    {
        //        Common.MessageBox.PrintMsg(panMsg, Common.MsgLevelEnum.attention, "进栏日期项不能为空.");
        //        return;
        //    }
        //    if (!DateTime.TryParse(txtBirthday.Text, out dateBirthday))
        //    {
        //        Common.MessageBox.PrintMsg(panMsg, Common.MsgLevelEnum.attention, "出生日期项不能为空.");
        //        return;
        //    }
        //    if (!Guid.TryParse(ddlPigPen.SelectedItem.Value, out pigPenId))
        //    {
        //        Common.MessageBox.PrintMsg(panMsg, Common.MsgLevelEnum.attention, "猪舍号不能为空.");
        //        return;
        //    }
        //    if (!Guid.TryParse(ddlPigType.SelectedItem.Value, out pigTypeId))
        //    {
        //        Common.MessageBox.PrintMsg(panMsg, Common.MsgLevelEnum.attention, "母猪类型不能为空.");
        //        return;
        //    }
        //    if (!int.TryParse(ddlSource.SelectedItem.Value, out sourceId))
        //    {
        //        Common.MessageBox.PrintMsg(panMsg, Common.MsgLevelEnum.attention, "母猪来源不能为空.");
        //        return;
        //    }
        //    if (!Guid.TryParse(ddlPropagateState.SelectedItem.Value, out propagateStateID))
        //    {
        //        Common.MessageBox.PrintMsg(panMsg, Common.MsgLevelEnum.attention, "母猪繁殖状态不能为空.");
        //        return;
        //    }
        //    int.TryParse(txthybridizationCount.Text.Trim(), out hybridizationCount);
        //    int.TryParse(txtPropagateCount.Text.Trim(), out propagateCount);
        //    Model.Sow sow = new Model.Sow();
        //    sow.HoggeryID = hoggeryId;
        //    sow.BitID = bitId;
        //    sow.PigPenID = pigPenId;
        //    sow.TypeID = pigTypeId;
        //    sow.SourceID = sourceId;
        //    sow.DateJoinFarm = dateJoin;
        //    sow.PropagateStateID = propagateStateID;
        //    sow.Brithdary = dateBirthday;
        //    sow.HybridizationCount = hybridizationCount;
        //    sow.PropagateCount = propagateCount;

        //    string retureValue = string.Empty;
        //    BLL.Sow bllSow = new BLL.Sow();
        //    string sowIdStr;
        //    try
        //    {
        //        bool result = bllSow.Add(sow, out retureValue, out sowIdStr);

        //        log4net.ILog log = log4net.LogManager.GetLogger(new System.Diagnostics.StackFrame(0).GetMethod().Name);
        //        Com.HoggeryLog businessLog = new Com.HoggeryLog()
        //        {
        //            HoggeryID = hoggeryId,
        //            PigId = sowIdStr,
        //            BusinessLogDate = System.DateTime.Now,
        //            LogType = OnlineManagement.Web.Com.HoggeryLogType.SowAdd,
        //        };

        //        if (result)
        //        {
        //            businessLog.Message = string.Format("新加{0}号母猪", bitId);
        //            Common.MessageBox.PrintMsg(panMsg, Common.MsgLevelEnum.success, retureValue);
        //        }
        //        else
        //        {
        //            Common.MessageBox.PrintMsg(panMsg, Common.MsgLevelEnum.error, retureValue);
        //        }
        //        businessLog.LogComment = retureValue;
        //        log.Info(businessLog);
        //        ClearControlValue();

        //    }catch(Exception ex){
        //        Common.MessageBox.PrintMsg(panMsg, Common.MsgLevelEnum.error, Common.PubMsg.ServerError);
        //    }
        //}

        void btnSearch_Click(object sender, EventArgs e)
        {
            string bitId = txtSearchBitId.Text;
            string customerId = txtSearchCustmerId.Text;
            string statueId = ddlSearchStatu.SelectedItem.Value;
            System.Text.StringBuilder whereStr = new System.Text.StringBuilder();
            whereStr.Append(" 1=1 ");
            if(!string.IsNullOrEmpty(bitId)){
                whereStr.AppendFormat(" AND BitID='{0}' ",bitId);
            }
            if(!string.IsNullOrEmpty(customerId)){
                whereStr.AppendFormat(" AND CustomizeID LIKE '%{0}%'", customerId);
            }
            if(statueId!="0"){
                whereStr.AppendFormat(" AND PropagateStateOrder ={0}", statueId);
            }
           
            BindRepeater(HoggeryID,whereStr.ToString());
        }

        void rptShow_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DataRowView dv = (DataRowView)e.Item.DataItem;

                int order = int.Parse(dv["PropagateStateOrder"].ToString());
                DropDownList ddl = e.Item.FindControl("ddlOper") as DropDownList;
                Label lb = e.Item.FindControl("lbAvgPropagetCount") as Label;
                BindAction(order, ddl);

                Label lbExpectedDate = e.Item.FindControl("lbExpectedDate") as Label;
                if (string.IsNullOrEmpty(dv["ExpectedDate"].ToString()))
                {
                    //lbExpectedDate.ForeColor = System.Drawing.Color.Red;
                    lbExpectedDate.Text = Common.PubConstant.EmptyString;
                }
               

                bool isWarn=false;
                bool.TryParse(dv["IsWarn"].ToString(),out isWarn);
                if(isWarn){
                    ((System.Web.UI.HtmlControls.HtmlTableRow)e.Item.FindControl("tRow")).Style.Add("color", "Red");
                }
                if (string.IsNullOrEmpty(dv["AvgPropagetCount"].ToString()))
                {
                    lb.Text = Common.PubConstant.EmptyString;
                }
                else {
                    lb.Text = dv["AvgPropagetCount"].ToString();
                }
            }
        }
       
        private void BindAction(int order,DropDownList ddl) {
            try
            {
                DataSet ds = GetActionsData();
                EnumerableRowCollection<DataRow> query = null;
                if (ds != null && ds.Tables.Count > 0)
                {
                    query = from data in ds.Tables[0].AsEnumerable()
                            where data.Field<Byte>("PropagateStateOrder") == order
                            select data;
                }
                if (query != null)
                {
                    ddl.DataSource = query.AsDataView();
                    ddl.DataTextField = "ActionName";
                    ddl.DataValueField = "ActionOrder";
                    ddl.DataBind();
                    ListItem item = new ListItem("--选择--", "0");
                    ddl.Items.Insert(0, item);
                }
            }catch(Exception ex){
                Common.MessageBox.PrintMsg(panMsg, Common.MsgLevelEnum.error, ex.Message);
            }
        }

        private DataSet GetActionsData() {
            BLL.Sow bllSow = new BLL.Sow();
            DataSet ds = bllSow.GetSowActions();
            return ds;
        }
       
        private void BindRepeater(int hoggeryId,string whereStr)
        {
            int rCount;
            rptShow.PageSize = 5;
            rptShow.PageLink = strPath;
            rptShow.CurrentPage = Request.QueryString["page"] == null ? 1 : int.Parse(Request.QueryString["page"] == "" ? "1" : Request.QueryString["page"]);
           
            DataSet ds=GetDataPaging(hoggeryId, rptShow.PageSize,rptShow.CurrentPage,whereStr,string.Empty, out rCount);
            if (ds != null && ds.Tables.Count > 1)
            {
                rptShow.DataSource = ds.Tables[1];
                rptShow.RecordCount = rCount;
                rptShow.DataBind();
            }
            else {
                rptShow.DataSource = new DataSet();
                rptShow.RecordCount = 0;
                rptShow.DataBind();
            }
          
        }

        private DataSet GetDataPaging(int hoggeryId, int pageSize, int currentPage,string whereStr,string orderByStr, out int rCount)
        {
            BLL.Sow bllSow = new BLL.Sow();
            DataSet ds= bllSow.GetSowDataPaging(hoggeryId, pageSize, currentPage, whereStr, orderByStr, out rCount);
            return ds;
        }


    }
    
}